import React from 'react';
import { connect } from 'react-redux';
import { messages, deepFullCopy } from 'share/common'
import customField from 'share/customField'
import 'styles/approve/edit-content.scss'
import { Form, Affix, Button, message, Tooltip, Icon } from 'antd';
const FormItem = Form.Item;
import requestService from 'containers/request/request.service'

class EditContent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custFormValues: [],
      formIsChange: false,//表单是否已经改动且未保存
      isLoading: false, //保存的loading
      originalFormInfo: {},
      formDetailValues: {},
      copyDefaultValues: {},
      jobInfo: {},
      applicationOID: '',
      info: {},
      jobInfo: {},
      fafangleixingFlag: false
    }
    this.state.copyDefaultValues.checkedChange = this.checkedChange;
  }

  componentWillMount() {
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.isShowEdit === this.props.params.isShowEdit) {
      return
    } else {
      this.setState({
        custFormValues: this.props.params.custFormValues,
        originalFormInfo: this.props.params.originalFormInfo,
        formDetailValues: deepFullCopy(this.props.params.originalFormInfo),
        applicationOID: this.props.params.applicationOID,
        info: this.props.params.info,
        jobInfo: this.props.params.jobInfo
      })
      this.copyDefaultCust(this.props.params.info, 'edit');
    }
  };

  // 保存
  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          isLoading: true
        }, () => {
          const {custFormValues, info} = this.state
          let isChange = false;
          custFormValues.map(item => {
            if (item.messageKey === 'select_company') {
              if (info.formCode === 'SQ004') {
                item.value = values[item.fieldOID][0].companyOID
                item.showValue = values[item.fieldOID][0].name
              } else {
                item.value = values[item.fieldOID].key ? values[item.fieldOID].key : values[item.fieldOID]
                item.showValue = values[item.fieldOID].label ? values[item.fieldOID].label : ''
              }
            } else if (item.messageKey === 'attachment') {
              if (typeof values[item.fieldOID] === 'string') {
                item.value = values[item.fieldOID]
                item.showValue = values[item.fieldOID]
              } else {
                item.value = JSON.stringify(values[item.fieldOID])
                item.showValue = JSON.stringify(values[item.fieldOID])
              }
            } else if (item.messageKey === 'cust_list') {
              if(item.fieldCode=== "fafangleixing"){
                item.value = values[item.fieldOID]
                return;
              }
              if (item.value !== values[item.fieldOID]) {
                isChange = true;
              }
              item.value = values[item.fieldOID]
            } else {
              item.value = values[item.fieldOID]
            }
          })
          info.custFormValues = custFormValues
          requestService.saveExpenseRequest(info).then(res => {
            this.setState({isLoading: false})
            if (isChange && info.formCode === 'SQ002') {
              requestService.deleteApplicationGift(this.props.params.id).then(res => {
                if (res.status === 200) {
                  this.props.close(true)
                  // console.log("isChange", isChange)
                  message.success(messages('request.key779'/*保存成功*/))
                }
              })
            } else {
              this.props.close(true)
              // console.log("isChange", isChange)
              message.success(messages('request.key779'/*保存成功*/))
            }
          }).catch(() => {
            this.setState({isLoading: false})
          })
        })
      }
    })
  }

  closeSlide = () => {
    this.props.close();
  };

  // 费用承担公司改变时，费用承担部门和费用确认人要置空
  onCompanyChange = () => {
    let { custFormValues } = this.state
    custFormValues && custFormValues.map(item => {
      let obj = {}
      if (item.messageKey === 'select_cost_center' || item.messageKey === 'select_user') {
        item.value = ''
        item.showValue = ''
        obj[item.fieldOID] = ''
      }
      this.props.form.setFieldsValue(obj)
    })
    this.setState({
      custFormValues
    })
  }

  // 费用承担部门改变时，费用确认人要置空
  onDepartmentChange = (field, e, all) => {
    if (e && all.id && field.fieldName === '费用承担部门') {
      let { custFormValues } = this.state
      custFormValues && custFormValues.map(item => {
        let obj = {}
        if (item.messageKey === 'select_user') {
          item.value = ''
          item.showValue = ''
          obj[item.fieldOID] = ''
          this.props.form.setFieldsValue(obj)
        }
        if (item.messageKey === 'select_cost_center' && item.fieldName === '费用承担部门') {
          item.value = all.costCenterItemOID;
          item.showValue = all.name;
          obj[item.fieldOID] = [{ name: all.name, costCenterItemOID: all.costCenterItemOID }];
          this.props.form.setFieldsValue(obj)
        }
      })
      this.setState({
        custFormValues
      })
    }
  }

  checkedChange = (field, value) => {
    console.log('部分表单控件value值变化监听函数')
    let { custFormValues } = this.state;
    let custForm = custFormValues;
    if(field.fieldCode === 'kq'){
      if(value==='001'){ //选择实体卡券
        this.setState({fafangleixingFlag:false})
      } else if(value==='002') {
        this.setState({fafangleixingFlag:true})
        custForm.map((i)=> {
          if (i.fieldCode === 'fafangleixing') {
            i.required = true;
            i.valid = true;
          }
        });
      }else{
        this.setState({fafangleixingFlag:false})
      }
    }
  }

   /**
   * 备份默认值，做修改参照基准
   * @param res
   * @param status 表单状态 edit create
     */
   copyDefaultCust = (res, status) => {
    let dev = [];
    dev.checkedChange = this.checkedChange;//设置监听
    //添加更改状态单子不可编辑 申请人，参与人，外部参与人数量
    if (status === 'edit') {
      res.custFormValues.map(m => {
        dev.push({
          value: m.value,
          messageKey: m.messageKey,
          formValueOID: m.formValueOID,
          fieldOID: m.fieldOID,
          fieldName: m.fieldName,
          required: m.required,
          formType: this.state.formType,
          showName: { name: m.showValue },
          initValue: { value: m.value, name: m.showValue },
          showValue: m.showValue,
          dataSource: m.dataSource,
          fieldContent: m.fieldContent,
          fieldConstraint: m.fieldConstraint,
          fieldCode: m.fieldCode,
        });
      });
      this.setState({ copyDefaultValues: dev });
    }
  };

  render() {
    const { custFormValues, isLoading, originalFormInfo, formDetailValues, jobInfo, copyDefaultValues, fafangleixingFlag } = this.state;
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    let isEdit = originalFormInfo.formCode === 'SQ021' ? true : false
    let fieldDefaultValue = {costCenterItemOID: ''}
    let customFormFields = originalFormInfo.customFormFields   
    custFormValues && custFormValues.map(item => {
      if (item.messageKey === 'select_cost_center' && item.fieldName === '费用承担部门') {
        fieldDefaultValue.costCenterItemOID = item.value;
        fieldDefaultValue.name = item.showValue;
      }
      customFormFields.map(itemFields => {
        if (item.fieldName === itemFields.fieldName) {
          item.dataPool = itemFields.dataPool
          item.formField = itemFields.formField
        }
      })
    });
    custFormValues.map((i,index)=> {
      if (i.fieldCode === 'luojipanduan') {
        custFormValues.splice(index, 1)
      }
    });
    return (
      <div className="approve-edit">
        <Form className='form-container'>
        {
            custFormValues && custFormValues.filter(i=>{
              if(!fafangleixingFlag && i.fieldCode == 'fafangleixing'){
                return;
              }
              return i;
            }).map((field, index) => {
                let unionCompanyFlag = false
                if (isEdit) {
                  if (field.messageKey !== 'input') {
                    field.isReadOnly = true
                  }
                  if (field.messageKey === 'select_cost_center') {
                    field.SQ021Edit = true
                  }
                }
                if (field.messageKey === 'select_company') {
                  if (field.fieldConstraint) {
                    let fieldConstraint = JSON.parse(field.fieldConstraint)
                    if (fieldConstraint.unionCompany) {
                      field.value = field.value && field.value.length > 0 ? [{ companyOID: field.value, name: field.showValue }] : []
                      unionCompanyFlag = true
                    }
                  }
                }
                //label
                let label = field.fieldName;
                if (field.messageKey === 'number') {
                  label = `${field.fieldName}${JSON.parse(field.fieldContent || '{}').unit && `(${JSON.parse(field.fieldContent || '{}').unit})`}`
                }
                let formFieldInfo = originalFormInfo.customFormFields && originalFormInfo.customFormFields.filter((item) => item.fieldOID === field.fieldOID)[0]
                if (formFieldInfo && formFieldInfo.fieldTips) {
                  label = (<span>
                    {label}&nbsp;
                    <Tooltip title={formFieldInfo.fieldTips}>
                      <Icon type="question-circle-o" />
                    </Tooltip>
                  </span>);
                }
                //rules
                let maxLength = (field.messageKey === 'remark' || field.messageKey === 'textArea' || field.messageKey === 'text_area') ? 200 :
                  (field.messageKey === 'input' ? 50 : undefined);
                maxLength = field.messageKey === 'title' ? 500 : maxLength;
                let rules = [{
                  required: field.required,
                  message: messages('common.can.not.be.empty', {name: field.fieldName})
                }];
                maxLength && rules.push({
                  max: maxLength,
                  message: messages('common.max.characters.length', {max: maxLength})
                });
                (field.messageKey === 'out_participant_name' || field.messageKey === 'external_participant_name') && rules.push({
                    validator: (rule, value, callback) => {
                      let emptyItem = '';
                      value && value.map(item => {
                        if (!item.name) {
                          emptyItem = messages('request.key100'/*姓名*/);
                          return
                        }
                        if (!item.certificateNo) {
                          emptyItem = messages('request.key101'/*证件号*/)
                        }
                      });
                      if (!emptyItem) {
                        callback();
                        return
                      }
                      callback(messages('common.can.not.be.empty', {name: emptyItem}))
                    }
                  });
                return (
                    <div key={index}>
                      <FormItem {...formItemLayout} label={label || ' '} key={field.fieldOID} colon={!!label}>
                        {((field.messageKey === 'total_budget' && formType != 2005) || field.messageKey === 'average_budget') && <span>{this.props.company.baseCurrency}</span>}
                        {getFieldDecorator(field.fieldOID, {
                          rules,
                          valuePropName: field.messageKey === 'switch' ? 'checked' : 'value',
                          initialValue: unionCompanyFlag ? field.value : customField.getInitialValue(field)
                        })(
                          customField.renderForm({
                            field,
                            fieldDefaultValue,
                            formDetail: formDetailValues,
                            copyValue: copyDefaultValues,
                            formValues: getFieldsValue(),
                            jobId: formDetailValues.id,
                            jobInfo,
                            propsParams: {
                              formDataId: formDetailValues.id,
                              pkId: formDetailValues.id,
                              departmentOID: jobInfo.departmentOID,
                              companyOID: jobInfo.companyOID
                            },
                            onCompanyChange: this.onCompanyChange,
                            onDepartmentChange: this.onDepartmentChange
                          })
                        )}
                      </FormItem>
                    </div>
                )
            })
        }
      </Form>
        <Affix className="type-affix" offsetBottom={0}>
          <Button type="primary" loading={isLoading} onClick={this.handleSave}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="type-btn" onClick={this.props.close}>{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}
const wrappedEditContent = Form.create()(EditContent);
export default connect(mapStateToProps)(wrappedEditContent)
